﻿/*
'Description:黎阳工控网数据交换系统帮助类
'Copyright (c) : 通力凯顿（北京）系统集成有限公司
'Writer:Wangjh 
'create Date:20230505
'Rewriter:
'Rewrite Date:
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UFC.DBUtility;
using UFC.Common;
using System.Configuration;
using Newtonsoft.Json;
using System.Data;
using SyslogNet.Client;
using SyslogNet.Client.Serialization;
using SyslogNet.Client.Transport;
using System.IO;

namespace SendIndustrialNetwork
{
   public class LYIndustryFileExchangeHelper
    {

        private static readonly string appAuthUrl = ConfigurationManager.AppSettings["appAuthUrl"];//认证接口
        private static readonly string appId = ConfigurationManager.AppSettings["appId"];//应用ID
        private static readonly string strPassword = SM3Util.ToSM3HexStr(ConfigurationManager.AppSettings["password"]);//SM3国密加密方式
        private static readonly string fileUploadUrl = ConfigurationManager.AppSettings["fileUploadUrl"];//文件上传接口
        private static readonly string filePersons = ConfigurationManager.AppSettings["filePersons"];//传文件相关的人:起草人，审批人，签发人

        private static readonly string syslogIp = ConfigurationManager.AppSettings["SM_SysLog_IP"];//syslog日志IP信息 
        private static readonly string m_BackFilePath = ConfigurationManager.AppSettings["backFilePath"];//文件备份的位置

        public class Rspresult
        {
            public string code { set; get; }
            public string token { set; get; }
            public string msg { set; get; }
        }
        /// <summary>
        /// 获取token
        /// </summary>
        public static string GetAppAuthToken(string port)
        {
            var token = CacheHelper.GetToken("token_" + port);
            if (string.IsNullOrWhiteSpace(token))
            {
                string appauthUrl = string.Format(appAuthUrl, port);
                string rspStr = HttpWebRequestHelper.HttpPostSync(appauthUrl, JsonConvert.SerializeObject(new { appId = appId, password = strPassword }), "application/json", "", new Dictionary<string, string>());
                LogHelp.WriteLog("GetAppAuthToken" + (port == "11012" ? "三坐标：" : "热表：") + rspStr);
                if (!string.IsNullOrWhiteSpace(rspStr))
                {
                    var jsonObj = JsonConvert.DeserializeObject<Rspresult>(rspStr);
                    if (jsonObj.code == "200")
                    {
                        CacheHelper.SetToken("token_" + port, jsonObj.token);
                        token = jsonObj.token;
                    }
                }
            }
            return token;
        }

        /// <summary>
        /// 文件上传
        /// </summary>
        public static  string FileUpload(string port, string fileName, string strXml,string fileNotes)
        {
            var Token = GetAppAuthToken(port);
            if (!string.IsNullOrWhiteSpace(Token))
            {
                var spr = filePersons.Split(',')[1];
                Dictionary<string, string> dic = new Dictionary<string, string>();
                dic.Add("Token", Token);//认证接口返回的token凭证--
                dic.Add("FileName", System.Web.HttpUtility.UrlEncode(fileName));//文件名，包含文件的路径
                dic.Add("WenjianqIcaoren", System.Web.HttpUtility.UrlEncode(filePersons.Split(',')[0]));//文件起草人
                dic.Add("Shenpiren", System.Web.HttpUtility.UrlEncode(port=="11013"?spr.Split('|')[1]:spr.Split('|')[0]));//审批人
                dic.Add("Miji", "4");//密级
                dic.Add("Baomiqixian", "10,0,0");//保密期限
                dic.Add("Qianfaren", System.Web.HttpUtility.UrlEncode(filePersons.Split(',')[2]));//签发人
                dic.Add("Wenjiansanliezhi", SM3Util.ToSM3HexStr(strXml));//文件散列值
                dic.Add("Beizhu", System.Web.HttpUtility.UrlEncode(fileNotes));//备注
                var FileUploadUrl = string.Format(fileUploadUrl, port);
                string rspStr = HttpWebRequestHelper.HttpPostSync(FileUploadUrl, strXml, "", "", dic);//@"{'msg':'文件上传成功','code':'200'}"; // 

                return rspStr;
            }
            else {
                return "{'msg':'未获取到token','code':'500'}";
            }
        }

        /// <summary>
        /// 使用UDP方式、发送日志给日志系统
        /// </summary>
        /// <param name="message">日志消息内容</param>
        /// <param name="hostname">日志系统IP地址</param>
        /// <param name="port">端口</param>
        public static void SendSysLogByUDP(string regCode, string operater, string fileName, string fileSuffix, string fileSize, string desc)
        { 
            Dictionary<string, string> LogDic = new Dictionary<string, string>();
            LogDic.Add("operateUser", operater);//操作人
            LogDic.Add("sourceip", "20.10.22.33");//源地址
            LogDic.Add("destip", "20.12.18.11");//目的地址
            LogDic.Add("fileType", fileSuffix);//文件类型
            LogDic.Add("fileNo", "");//文件序号
            LogDic.Add("fileName", fileName);//文件名称
            LogDic.Add("fileSize", fileSize);//文件大小
            LogDic.Add("result", regCode == "200" ? "上传成功" : "上传失败");//结果
            LogDic.Add("desc", desc);//文件描述
            LogDic.Add("date", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:sss"));//时间 

            SyslogMessage msg = new SyslogMessage(
                DateTimeOffset.Now,
                Facility.LogAlert, // Facility - LogAlert
                Severity.Critical, // Severity - Critical
                Environment.MachineName, // MachineName
                "MES", // AppName
                 null, // ProcId
                "Mes_MsgType", // Message type name
                JsonConvert.SerializeObject(LogDic)); // message to be sent---
            ISyslogMessageSerializer serializer = (ISyslogMessageSerializer)new SyslogRfc3164MessageSerializer();//SyslogRfc5424MessageSerializer--SyslogRfc3164MessageSerializer
            ISyslogMessageSender sender = (ISyslogMessageSender)new SyslogUdpSender(syslogIp.Split(':')[0], int.Parse (syslogIp.Split(':')[1]));//SyslogUdpSender--SyslogTcpSender
            sender.Send(msg, serializer);

        }

        
       /// <summary>
       /// 转移文件
       /// </summary>
       /// <param name="fi"></param>
       /// <param name="backName"></param>
        public static void MoveBackFile(FileInfo fi,string backName) {
            string extension = fi.Extension;
            string name = fi.Name.Replace(extension,"");
            File.Copy(fi.FullName,m_BackFilePath+"\\"+ name + backName + DateTime.Now.ToString("yyyyMMddHHmmssfff")+extension, true);
            File.Delete(fi.FullName);
        }
    }
}
